from app.datafactory.models import Project,session,RequestsInfo,ScriptStep,CustomFunc
from app.utils import is_duplicate
class ProjectDao:
    """
    Project DAO
    """
    def __init__(self):
        self.session = session

    def get_projects(self,pageNum=1,pageSize=10):
        """
        Get all projects
        """

        pageNum = int(pageNum)

        pageSize = int(pageSize)
        query = self.session.query(Project).filter(Project.is_del == 0)
        total = query.count()
        max_page = (total + pageSize - 1) / pageSize
        if  int(pageNum) > max_page:
            return 0,[]
        else:
            return total,query.order_by(Project.update_time.desc()).paginate(page=int(pageNum), per_page=int(pageSize))

    def get_project(self, project_id):
        """
        Get a project by name
        """
        result =   self.session.query(Project).filter(Project.is_del == 0).filter(Project.id == project_id).first()
        if result is None:
        # 处理查询结果为空的情况
            return None
        else:
        # 处理查询结果不为空的情况
            return result.as_dict()

    def create_project(self, name,description):
        """
        Create a project
        """
        project = Project(name=name,description=description)
        self.session.add(project)
        self.session.commit()
        return True

    def update_project(self, project_id,project_new_name,project_desc):
        """
        Update a project
        """

        project = self.session.query(Project).filter(Project.is_del == 0).filter(Project.id == project_id).first()
        if project:
            project.name = project_new_name
            project.description = project_desc
            self.session.commit()
            return project
        else:
            return None

    def delete_project(self, project_id):
        """
        Delete a project
        """
        project = self.session.query(Project).filter(Project.is_del == 0).filter(
            Project.id == project_id).first()
        if project:

            project.is_del = True
            self.session.commit()
            return project
        else:
            return None
    def name_duplicate(self,name):
        return is_duplicate(Project, ['name','is_del'], [name,0])



class ReqinfoDao:
    """
    RequestsInfo DAO
    """
    def __init__(self):
        self.session = session

    def get_ReqInfo_list(self,pageNum=1,pageSize=10):
        """
        Get all RequestsInfos
        """
        pageNum = int(pageNum)
        pageSize = int(pageSize)
        query = self.session.query(RequestsInfo).filter(RequestsInfo.index == 1,RequestsInfo.is_del == 0)
        total = query.count()
        max_page = (total + pageSize - 1) / pageSize
        if  int(pageNum) > max_page:
            return 0,[]
        else:
            return total,query.order_by(RequestsInfo.update_time.desc()).paginate(page=int(pageNum), per_page=int(pageSize))

    def get_ReqInfo(self, ReqInfo_title):
        """
        Get a RequestsInfo by name
        """
        return self.session.query(RequestsInfo).filter(RequestsInfo.is_del == 0,RequestsInfo.title == ReqInfo_title).all()

    def create_ReqInfo(self, reqinfo,title):
        """
        Create a RequestsInfo
        """
        list1 = []
        for info in reqinfo:

            list1.append(RequestsInfo(title=title,
                                      index=info["index"],
                                      method=info["method"],
                                      url=info["url"],
                                      headers=info["headers"],
                                      params=info["params"],
                                      payload=info["payload"],
                                      data=info["data"],
                                      res=info["res"],
                                      ))

        self.session.add_all(list1)
        self.session.commit()

        return True
    def update_ReqInfo(self, RequestsInfo_id,RequestsInfo_new_name,RequestsInfo_desc):
        """
        Update a RequestsInfo
        """

        ReqInfo = self.session.query(RequestsInfo).filter(RequestsInfo.is_del == 0).filter(RequestsInfo.id == RequestsInfo_id).first()
        if RequestsInfo:
            RequestsInfo.name = RequestsInfo_new_name
            RequestsInfo.description = RequestsInfo_desc
            self.session.commit()
            return RequestsInfo
        else:
            return None

    def delete_ReqInfo(self, ReqInfo_title):
        """
        Delete a RequestsInfo
        """
        ReqInfo_list = self.session.query(RequestsInfo).filter(RequestsInfo.is_del == 0,
            RequestsInfo.title == ReqInfo_title).all()
        if ReqInfo_list:
            for ReqInfo in ReqInfo_list:
                ReqInfo.is_del = True
            self.session.commit()
            return ReqInfo_list
        else:
            return None
    def name_duplicate(self,title):
        if self.session.query(RequestsInfo).filter(RequestsInfo.title == title,RequestsInfo.is_del == 0).first():

            return True
        
class ScriptDao:
    """
    ScriptStep DAO
    """
    def __init__(self):
        self.session = session

    def get_Script_list(self,pageNum=1,pageSize=10):
        """
        Get all ScriptInfos
        """
        pageNum = int(pageNum)
        pageSize = int(pageSize)
        query = self.session.query(ScriptStep,Project.name).join(Project).filter(ScriptStep.index == 1,ScriptStep.is_del == 0)
        total = query.count()
        max_page = (total + pageSize - 1) / pageSize
        if  int(pageNum) > max_page:
            return 0,[]
        else:
            query_list = query.order_by(ScriptStep.update_time.desc()).paginate(page=int(pageNum), per_page=int(pageSize))
            result = []
            for query in query_list:
                script = query[0]
                script.projectName = query[1]
                result.append(script)
            return total,result

    def get_Script(self, project_id,scriptName):
        """
        Get a ScriptStep by name
        """


        return self.session.query(ScriptStep).filter(ScriptStep.is_del == 0,ScriptStep.project_id == project_id,ScriptStep.scriptName == scriptName).all()

    def create_Script(self, scriptName,script_list, project_id):
        """
        Create a ScriptStep
        """
        list1 = []
        for info in script_list:

            list1.append(ScriptStep(scriptName=scriptName,
                                    project_id=project_id,
                                    index=info["index"],
                                    method=info["method"],
                                    url=info["url"],
                                    headers=info["headers"],
                                    params=info["params"],
                                    payload=info["payload"],
                                    data=info["data"],
                                    res=info["res"],
                                      ))

        self.session.add_all(list1)
        self.session.commit()
        return True
    def update_Script(self, project_id,scriptName,script_data):
        """
        Update a ScriptStep
        """

        ScriptSteps = self.session.query(ScriptStep).filter(ScriptStep.is_del == 0).filter(
            ScriptStep.project_id == project_id,
            ScriptStep.scriptName == scriptName).all()

        if ScriptSteps:

            for script,new_data in  zip(ScriptSteps,script_data):
                script.index = new_data["index"]
                script.method = new_data["method"]
                script.url = new_data["url"]
                script.headers = new_data["headers"]
                script.params = new_data["params"]
                script.payload = new_data["payload"]
                script.data = new_data["data"]
                script.res = new_data["res"]


            self.session.commit()
            return ScriptSteps
        else:
            return None

    def delete_Script(self, project_id,scriptName):
        """
        Delete a ScriptStep
        """
        Script_list = self.session.query(ScriptStep).filter(
            ScriptStep.is_del == 0,
            ScriptStep.project_id == project_id,
            ScriptStep.scriptName == scriptName).all()
        if Script_list:
            for Script in Script_list:
                Script.is_del = True
            self.session.commit()
            return Script_list
        else:
            return None
    def name_duplicate(self,project_id,scriptName):
        if self.session.query(ScriptStep).filter(ScriptStep.project_id == project_id,
                                                 ScriptStep.scriptName == scriptName,
                                                 ScriptStep.is_del == 0).first():

            return True


class CustomFuncDao:
    """
    CustomFunc DAO
    """
    def __init__(self):
        self.session = session

    def get_CustomFuncs(self,pageNum=1,pageSize=10):
        """
        Get all CustomFuncs
        """

        pageNum = int(pageNum)

        pageSize = int(pageSize)
        query = self.session.query(CustomFunc).filter(CustomFunc.is_del == 0)
        total = query.count()
        max_page = (total + pageSize - 1) / pageSize
        if  int(pageNum) > max_page:
            return 0,[]
        else:
            return total,query.order_by(CustomFunc.update_time.desc()).paginate(page=int(pageNum), per_page=int(pageSize))

    def get_CustomFunc(self, FuncName):
        """
        Get a CustomFunc by name
        """
        result =   self.session.query(CustomFunc).filter(CustomFunc.is_del == 0,CustomFunc.FuncName == FuncName).first()
        if result is None:
        # 处理查询结果为空的情况
            return None
        else:
        # 处理查询结果不为空的情况

            return result.as_dict()

    def create_customfunc(self,FuncName,FuncBody,description):
        """
        Create a CustomFunc
        """
        customfunc = CustomFunc(FuncName=FuncName,FuncBody=FuncBody,description=description)
        self.session.add(customfunc)
        self.session.commit()
        return True

    def update_customfunc(self, id,FuncName,FuncBody,description):
        """
        Update a CustomFunc
        """

        customfunc = self.session.query(CustomFunc).filter(CustomFunc.is_del == 0).filter(CustomFunc.id == id).first()
        if customfunc:
            customfunc.FuncName = FuncName
            customfunc.FuncBody = FuncBody
            customfunc.description = description
            self.session.commit()
            return customfunc
        else:
            return None

    def delete_CustomFunc(self, id, FuncName):
        """
        Delete a CustomFunc
        """
        custofunc = self.session.query(CustomFunc).filter(CustomFunc.is_del == 0).filter(
            CustomFunc.id == id,
            CustomFunc.FuncName == FuncName).first()
        if custofunc:

            custofunc.is_del = True
            self.session.commit()
            return custofunc
        else:
            return None
    def name_duplicate(self,FuncName):
        if self.session.query(ScriptStep).filter(CustomFunc.FuncName == FuncName,
                                                 CustomFunc.is_del == 0).first():

            return True